<!-- 
项目汇总
-->
<template>
  <ContainerLayout class="human-resource-statistics">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="部门" v-if="false">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="项目" v-if="false">
          <el-select v-model="projectValue" placeholder="请选择项目" style="width: 180px" :max-collapse-tags="1" multiple clearable collapse-tags>
            <template #header>
              <el-checkbox v-model="checkAllProject" :indeterminate="indeterminateProject" @change="handleCheckAllProject">全部</el-checkbox>
            </template>
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" label-width="80px">
          <el-select v-model="projectStatusValue" placeholder="请选择项目" style="width: 120px" clearable>
            <el-option v-for="item in projectStatus" :key="item.dictCode" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container" ref="tableContainer">
      <el-scrollbar :height="scrollbarHeight" always>
        <div v-for="tableItem in tableList" class="table-cells">
          <div class="table-wrap" ref="tableWrap">
            <el-table ref="dataTable" :data="tableItem.tableData" :height="tableHeight" style="width: 100%" border scrollbar-always-on header-cell-class-name="table-header-row" empty-text="没有数据">
              <el-table-column prop="id" label="ID" width="80" fixed> </el-table-column>
              <el-table-column prop="projectCategory" width="120" fixed>
                <template #header>
                  <div>Show Type</div>
                  <div>项目类型</div>
                </template>
                <template #default="scope">
                  {{ getProjectCategoryValue(scope.row.projectCategory) }}
                </template>
              </el-table-column>
              <el-table-column prop="projectStatus" width="120">
                <template #header>
                  <div>Show Status</div>
                  <div>项目状态</div>
                </template>
                <template #default="scope">
                  {{ getProjectStatusValue(scope.row.projectStatus) }}
                </template>
              </el-table-column>
              <el-table-column prop="cname" width="250">
                <template #header>
                  <div>Show Name</div>
                  <div>项目名称</div>
                </template>
              </el-table-column>
              <el-table-column prop="pmdUserNick" width="90">
                <template #header>
                  <div>制片</div>
                </template>
              </el-table-column>
              <el-table-column prop="clientName" width="120">
                <template #header>
                  <div>Client Name</div>
                  <div>客户名称</div>
                </template>
              </el-table-column>
              <el-table-column prop="startTime" width="120">
                <template #header>
                  <div>Start Date</div>
                  <div>起始时间</div>
                </template>
              </el-table-column>
              <el-table-column prop="endTime" width="220">
                <template #header>
                  <div>Actual planned Due Date</div>
                  <div>实际计划交付时间</div>
                </template>
              </el-table-column>
              <el-table-column prop="totalAssets" width="120">
                <template #header>
                  <div>Total Assets</div>
                  <div>总资产数</div>
                </template>
                <template #default="scope">
                  <ColumnTotalAssets :code="scope.row.code" />
                </template>
              </el-table-column>
              <el-table-column prop="totalShots" width="120">
                <template #header>
                  <div>Total Shots</div>
                  <div>总镜头数</div>
                </template>
                <template #default="scope">
                  <ColumnTotalShots :code="scope.row.code" />
                </template>
              </el-table-column>
              <el-table-column prop="completionPercentage" width="220">
                <template #header>
                  <div>Completion Percentage</div>
                  <div>项目完成百分比(含镜头和资产)</div>
                </template>
              </el-table-column>
              <el-table-column prop="totalBid" width="120">
                <template #header>
                  <div>Total Bid</div>
                  <div>报价 (人周)</div>
                </template>
              </el-table-column>
              <el-table-column prop="costToDate" width="150">
                <template #header>
                  <div>Cots To Date</div>
                  <div>已产生成本(人周)</div>
                </template>
              </el-table-column>
              <el-table-column prop="estOverallCost" width="220">
                <template #header>
                  <div>Est. Overall Cost</div>
                  <div>计划完成总成本(人周)</div>
                </template>
              </el-table-column>
              <el-table-column prop="estProfitMargin" width="220">
                <template #header>
                  <div>Est.Profit Margin</div>
                  <div>预计利润率(依据人周)</div>
                </template>
              </el-table-column>
              <el-table-column prop="riskValue" width="120">
                <template #header>
                  <div>Risk Value</div>
                  <div>项目风险值</div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" width="520">
                <template #header>
                  <div>Note</div>
                  <div>备注</div>
                </template>
                <template #default="scope">
                  <div class="remark-content">{{ scope.row.remark }}</div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="260">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="handlerClickEditPmdUser(scope.row)" :icon="Edit">编辑人员</el-button>
                  <el-button link type="primary" size="small" @click="handlerClickEdit(scope.row)" :icon="EditPen">编辑</el-button>
                  <el-button link type="primary" size="small" @click="handlerClickShowList(scope.row)" :icon="More">日志</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </ContainerLayout>
  <DrawerEditProjectRemark ref="drawerEditProjectRemark" @closeDrawer="handleCloseDrawerEditProjectRemark" />
  <DrawerEditProjectRemarkList ref="drawerEditProjectRemarkList" @closeDrawer="handleCloseDrawerEditProjectRemark" />
  <DialogProjectSummaryEditPmd ref="dialogProjectSummaryEditPmd" @closeDialog="handleCloseDialogProjectSummaryEditPmd" />
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import { Refresh, Search, Edit } from '@element-plus/icons-vue'
import type { CheckboxValueType } from 'element-plus'
import * as utils from '../utils'
import { useDeptStore, useProjectssStore, useProjectCategoryStore, useProjectStatusStore } from '../stores'
import http from '../http'
import DrawerEditProjectRemark from '../components/drawer/DrawerEditProjectRemark.vue'
import DrawerEditProjectRemarkList from '../components/drawer/DrawerEditProjectRemarkList.vue'
import DialogProjectSummaryEditPmd from '../components/dialog/DialogProjectSummaryEditPmd.vue'
import ColumnTotalAssets from '../components/ProjectSummary/ColumnTotalAssets.vue'
import ColumnTotalShots from '../components/ProjectSummary/ColumnTotalShots.vue'
import { EditPen, More } from '@element-plus/icons-vue'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import Lib from '../lib'

// CG-T
const cgtToken = ref('')

//
const deptList = ref(useDeptStore().getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const projectValue = ref<CheckboxValueType[]>([])
const projectStatusValue = ref(null)
const checkAllProject = ref(false)
const indeterminateProject = ref(false)
// const indeterminateProjectStatus = ref(false)
const tableList = ref<any>([])
const scrollbarHeight = ref(400)
const tableHeight = ref(400)
const tableContainer = ref(ref<HTMLElement | null>(null))
// 表格是否查询过
const isQueryed = ref(false)
const tableData = ref<any[]>([])
const projectTitle = ref<string>('')
const weeks = ref()
const tableColumnDate = ref<any[]>([])
const tableRows = ref<any[]>([])
const drawerEditProjectRemark = ref<InstanceType<typeof DrawerEditProjectRemark>>()
const drawerEditProjectRemarkList = ref<InstanceType<typeof DrawerEditProjectRemarkList>>()
const dialogProjectSummaryEditPmd = ref<InstanceType<typeof DialogProjectSummaryEditPmd>>()
const projectCategory = ref<Array<any>>(useProjectCategoryStore().getAllState() as any)
const projectStatus = ref<Array<any>>(useProjectStatusStore().getAllState() as any)
// const rowsHeadcount = ref<any[]>([])
// 项目列表
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
// 表单
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [] as Date[],
  deptIds: [] as string[] | number[],
  timelogCategory: '',
})

onMounted(async () => {
  if (tableContainer.value) {
    scrollbarHeight.value = tableContainer.value.offsetHeight
    tableHeight.value = tableContainer.value.offsetHeight
  }
  // await handleClickBtnReset()
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.date = [start, end]
  await getCGTInfo()
  // console.log('projectStatus', projectStatus.value)
})

const handlerClickEdit = (row: any) => {
  drawerEditProjectRemark.value!.openDrawer(row.id, row.cname, row.remark)
}
const handlerClickShowList = (row: any) => {
  drawerEditProjectRemarkList.value!.openDrawer(row.id, row.cname)
}
const handlerClickEditPmdUser = (row: any) => {
  dialogProjectSummaryEditPmd.value!.openDialog(row)
}
/**
 * 处理全选项目的逻辑
 *
 * @param val Checkbox 的值
 */
const handleCheckAllProject = (val: CheckboxValueType) => {
  indeterminateProject.value = false
  if (val) {
    projectValue.value = projectList.value.map((_) => _.id)
  } else {
    projectValue.value = []
  }
}
/**
 * 提交表单处理函数
 *
 * @returns {Promise<void>} 返回一个异步操作的Promise对象，无返回值
 */
const handleClickSubmit = async () => {
  // console.log('queryForm', queryForm)
  isQueryed.value = true
  tableData.value = []
  projectTitle.value = ''
  // console.log('queryForm.deptIds', queryForm.deptIds)

  // console.log('queryForm.date', queryForm.date)
  if (queryForm.date.length == 2) {
    const [start, end] = queryForm.date
    weeks.value = utils.getWeeksBetweenDates(start, end)

    // 设置表格列
    await setTableColumn()
    await getDeptList()
    await buildDataTable()
  }
}
/**
 * 点击重置按钮的处理函数
 *
 * @returns 返回一个 Promise，表示异步操作的结果
 */
const handleClickBtnReset = async () => {
  projectStatusValue.value = null
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.date = [start, end]
  await handleClickSubmit()
}

/**
 * 设置表格列
 *
 * @returns 无返回值
 */
const setTableColumn = async () => {
  // 设置 table 列
  tableColumnDate.value = []
  await new Promise((resolve) =>
    setTimeout(() => {
      tableColumnDate.value = [
        ...weeks.value.map((e: any) => {
          const start = utils.formatDate(e.start, 'yyyy-MM-dd')
          const end = utils.formatDate(e.end, 'yyyy-MM-dd')
          const startYear = utils.formatDate(e.start, 'yyyy')
          const endYear = utils.formatDate(e.end, 'yyyy')
          const startDay = utils.formatDate(e.start, 'MM-dd')
          const endDay = utils.formatDate(e.end, 'MM-dd')
          return { label: start, columnName: `${start} - ${end}`, start, end, startDay, endDay, startYear, endYear }
        }),
      ]
      resolve(true)
    }, 0)
  )
}
/**
 * 获取部门列表
 *
 * @returns 返回处理后的部门列表
 */
const getDeptList = async () => {
  const data = useDeptStore().getAllListState()
  const deptMap = new Map()
  const result: any = []

  // 先将所有部门信息存入Map，方便后续查找父部门名称
  data.forEach((item: any) => {
    deptMap.set(item.deptId, item)
  })

  data.forEach((item: any) => {
    const { deptId, parentId, deptName } = item
    const deptNamesExclude = '总经办,技术组'.split(',')
    if (parentId !== 100 && deptId !== 100 && deptNamesExclude.indexOf(deptName) === -1) {
      const parentItem = deptMap.get(parentId)
      const parentDeptName = parentItem.deptName
      result.push({ ...item, parentDeptName })
    }
  })

  tableRows.value = result
}

/**
 * 异步构建数据表格。
 *
 * @returns 无返回值。
 */
const buildDataTable = async () => {
  const params: any = {}
  if (projectStatusValue.value) {
    params.projectStatus = projectStatusValue.value
  }
  const tableData = await httpGetDataRow({
    path: '/dev-api/oa/project/listall',
    params,
  })
  tableList.value = [
    {
      tableTitle: '',
      tableData,
    },
  ]
}

const httpGetDataRow = async (queryParams: any) => {
  const [first] = weeks.value
  const [last] = weeks.value.slice(-1)
  const startTimelogDate = utils.formatDate(first.start, 'yyyy-MM-dd')
  const endTimelogDate = utils.formatDate(last.end, 'yyyy-MM-dd')
  const params = {
    pageSize: 99999,
    startTimelogDate,
    endTimelogDate,
  }
  if (queryParams.params) {
    Object.assign(params, queryParams.params)
    delete queryParams.params
  }
  const defaultParams = {
    method: 'GET',
    path: ``,
    params,
  }
  Object.assign(defaultParams, queryParams)
  const res = await http(defaultParams)
  return res.rows
}
/**
 * 处理关闭抽屉的事件
 */
const handleCloseDrawerEditProjectRemark = () => {
  handleClickSubmit()
}
const handleCloseDialogProjectSummaryEditPmd = () => {
  handleClickSubmit()
}

const getProjectCategoryValue = (val: any) => {
  const item = projectCategory.value.find((e: any) => e.dictValue == val)
  return item?.dictLabel || ''
}
const getProjectStatusValue = (val: any) => {
  const item = projectStatus.value.find((e: any) => e.dictValue == val)
  return item?.dictLabel || ''
}
const getCGTInfo = async () => {
  cgtToken.value = await Lib.CGT.getToken()
}

/**
 * 计算表格数据中的汇总信息
 *
 * @param param 包含表格列信息和数据的对象
 * @returns 返回汇总信息的数组，每个元素可能是字符串或VNode，表示该列的汇总结果
 */
// show-summary :summary-method="getSummaries"
// const getSummaries = (param: any) => {
//   const { columns } = param
//   const sums: any[] = []
//   columns.forEach((column: any, index: number) => {
//     if (index === 0) {
//       sums[index] = h('div', { class: 'total-headcount', style: 'width:270px;' }, ['Total Headcount'])
//       return
//     }
//     if (column.property) {
//       sums[index] = rowsHeadcount.value[column.property] || 0
//       // console.log('rowsHeadcount', rowsHeadcount.value)
//     }
//   })
//   sums[1] = ''
//   return sums
// }
</script>
<style lang="scss" scoped>
.human-resource-statistics {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .table-header-cell {
    writing-mode: vertical-lr;
    // line-height: 1;
  }
  .table-cell {
    cursor: pointer;
    width: 100%;
  }
  .remark-content {
    width: 100%;
    height: 100%;
    white-space: pre-line;
  }
}
</style>
